package com.cheng.spider.header;

import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ClassPathTxtHeaderSource extends AbstractHeaderSource {
    private static final Logger LOGGER = LoggerFactory.getLogger(ClassPathTxtHeaderSource.class);

    private String fileName;

    public ClassPathTxtHeaderSource(String fileName) {
        this.fileName = fileName;
    }

    protected void loadHeaders() {
        List<Header> list = new ArrayList<>();
        BufferedReader reader;
        String root = System.getProperty("user.dir");
        String path = root + File.separator + "src" + File.separator + "resources" + File.separator + fileName;
        LOGGER.info("正在读取Header：" + path);
        try {
            reader = new BufferedReader(new FileReader(path));
            String line = reader.readLine();
            while (line != null) {
                String[] headerKV = line.split(":");
                list.add(new BasicHeader(headerKV[0], headerKV[1]));
                line = reader.readLine();
            }
            LOGGER.info("加载header数：" + list.size());
        } catch (FileNotFoundException e) {
            throw new RuntimeException("file not found: " + fileName);
        } catch (IOException e) {
            throw new RuntimeException("IOException in read: " + fileName);
        }
        headers = new Header[list.size()];
        list.toArray(headers);
    }

}
